package com.google.code.avajhelpdesk.services;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.code.avajhelpdesk.entities.User;
import com.google.code.avajhelpdesk.exceptions.auth.AuthenticationException;
import com.google.code.avajhelpdesk.persistence.IGenericDAO;
import com.google.code.avajhelpdesk.persistence.IUserDAO;


@Service
public class UserService {
	
	private IUserDAO userDAO;
	
	public void setUserDAO(IUserDAO userDAO) {
		this.userDAO = userDAO;
	}
	
	private IGenericDAO genericDAO;

	public void setGenericDAO(IGenericDAO genericDAO) {
		this.genericDAO = genericDAO;
	}
	
	@Transactional
	public User authenticateUser(String username, String password) throws AuthenticationException {
		List userInstances = userDAO.findUser(username, password);
		if (userInstances.size() > 1) {
			throw new AssertionError("More than one user with same login/password pair exists");
		}
		if (userInstances.isEmpty()) {
			throw new AuthenticationException();
		}
		return (User) userInstances.get(0);
	}
	
	public User createUser(String username, String password, String firstName, String lastName) {
		User user = new User();
		user.setFirstName(firstName);
		user.setLastName(lastName);
		user.setPassword(password);
		user.setUsername(username);
		
		genericDAO.persist(user);
		
		return user;
	}
	
	public boolean isUserAlreadyExists(String username) {
		return !userDAO.findUser(username).isEmpty();
	}

	public List<User> findUsers(int first, int count, String property, boolean ascending) {
		return userDAO.findUsers(first, count, property, ascending);
	}

	public int userCount() {
		return genericDAO.count(User.class);
	}
}
